<template>
  <!-- 区域价格管理 -->
  <div>
    <div class="app-page">
      <org-tree
        class="orgTree"
        title="组织机构"
        :tree-data="treeData01"
        :mouse-button="false"
        :loading="$loadingPlugin.getTreeData"
        @currentChange="currentChange01"
      />
      <div class="content">
        <div>
          <el-table-form ref="form" class="merge-item">
            <el-form-item :table-form-merge="1.6">
              <el-input
                v-model="selectTimeDay"
                placeholder="请输入"
                clearable
                :disabled="selectTimeRangeFlage"
              >
                <el-select
                  slot="prepend"
                  v-model="selectTimeRange"
                  style="width: 120px;"
                >
                  <el-option label="自定义时间" value="1" />
                  <el-option label="近一个月" value="2" />
                  <el-option label="近三个月" value="3" />
                  <el-option label="近一年" value="4" />
                </el-select>
                <span slot="append"> 天未安检的客户</span>
              </el-input>
            </el-form-item>
            <el-form-item label="最后订气时间" :table-form-merge="2">
              <el-date-picker
                v-model="query.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="销售员">
              <el-select v-model="query.salesmanName" placeholder="请选择">
                <el-option label="请选择" value="" />
                <el-option
                  v-for="item in SalesmanNameMap"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户类型">
              <el-select
                v-model="query.csmTypes"
                multiple
                placeholder="请选择"
                collapse-tags
              >
                <el-option
                  v-for="item in customerTypeMap"
                  :key="item.value"
                  :label="item.desc"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <template v-slot:btns>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="search"
              >查询</el-button>
            </template>
          </el-table-form>
        </div>
        <div style="margin-bottom: 10px;" class="btn-group">
          <el-button
            type="primary"
            icon="el-icon-folder-opened"
            @click="batchExp"
          >导出</el-button>
        </div>
        <lb-table
          ref="lbTable"
          v-el-height-adaptive-table="{ bottomOffset: 10 }"
          class="table"
          border
          highlight-current-row
          element-loading-text="加载中"
          :column="tableData.column"
          :data="tableData.data"
          pagination
          :total="tableData.total"
          custom-column
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          @fetch="fetchData"
        />
      </div>
    </div>
  </div>
</template>

<script>
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap, parseTime } from '@/utils'
  import {
    organizationQueryList,
    selectUnCheckedCustomer,
    userByOrgidQuery,
    unCheckedCustomerExport,
    queryExportDomain
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import OrgTree from '@/views/components/OrgTree'

  export default {
    name: 'noCheckCsmSearch',
    components: {
      OrgTree
    },
    data() {
      return {
        treeData01: [],
        currentOrg: null,
        exportDomain: '',
        currentGoodsType: null,
        SalesmanNameMap: [],
        customerTypeMap: [
          { value: 1, desc: '居民用户', key: 'Resident_user' },
          { value: 2, desc: '商业用户', key: 'Business_user' },
          { value: 4, desc: '工业用户', key: 'GY_user' }
        ],
        query: {
          salesmanName: '',
          csmTypes: [1, 2, 4],
          orgSNNo: '001000000000000000000'
        },
        selectTimeRange: '1',
        selectTimeRangeFlage: false,
        selectTimeDay: 90,
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              width: 30
            },
            { label: '责任机构', prop: 'nearStationName', width: 150 },
            {
              label: '客户类型',
              prop: 'csmType',
              width: 100,
              render: (h, { row }) => (
              <span>
                {row.csmType &&
                  formatColumnMap(
                    this.customerTypeMap,
                    'value',
                    row.csmType,
                    'desc'
                  )}
              </span>
            )
            },
            { label: '客户编号', prop: 'csmCode', width: 100 },
            { label: '客户名称', prop: 'csmName', width: 100 },
            { label: '客户地址', prop: 'csmRgAddress', width: 300 },
            { label: '联系电话', prop: 'csmRgPhone', width: 120 },
            {
              label: '最后安检时间',
              prop: 'lastSCheckDt',
              width: 200,
              render: (h, { row }) => (
              <span>
                {row.lastSCheckDt &&
                  parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
            },
            { label: '销售员', prop: 'salesmanName', width: 120 },
            {
              label: '最后订气时间',
              prop: 'lastBuyDt',
              width: 200,
              render: (h, { row }) => (
              <span>
                {row.lastBuyDt &&
                  parseTime(row.lastBuyDt, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
            },
            { label: '配送员', prop: 'lastSender', width: 200 }
          ],
          data: []
        }
      }
    },
    watch: {
      selectTimeRange: function(val) {
        if (val === '1') {
          this.selectTimeRangeFlage = false
        } else {
          this.selectTimeRangeFlage = true
        }
        if (val === '2') {
          this.selectTimeDay = 30
        }
        if (val === '3') {
          this.selectTimeDay = 90
        }
        if (val === '4') {
          this.selectTimeDay = 365
        }
      }
    },
    created() {
      this.getTreeData01()
      this.getExportDomain()
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        console.log(this.selectTimeDay)
        if (this.selectTimeDay === '') {
          this.$message({
            message: '请输入天数！',
            type: 'warning'
          })
          return
        }
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.date && this.query.date.length > 0) {
          query.lastBuyDt = this.query.date[0]
          query.lastBuyDtEnd = this.query.date[1]
        }
        const nowDate = new Date()
        query.lastSCheckDt = new Date(
          nowDate.setDate(nowDate.getDate() - this.selectTimeDay)
        )
        delete query.date
        const res = await selectUnCheckedCustomer(query)
        this.tableData.data = res.data.rows
        this.tableData.total = res.data.total
      },
      getSalesmanName(orgId) {
        userByOrgidQuery({
          orgId: orgId,
          corpparm1: 1,
          utype: 64
        }).then(res => {
          this.SalesmanNameMap = res.data
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 获取组织机构数据
      async getTreeData01() {
        const res = await organizationQueryList({})
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData01 = getTreeData(data)
      },
      // 选择组织机构变化
      currentChange01(current) {
        this.query.orgSNNo = current.orgSNNo
        this.getSalesmanName(current.orgId)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then(res => {
          console.log(res)
          this.exportDomain = res.data
        })
      },
      batchExp() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const currentPage = this.$refs.lbTable.currentPage
          const pageSize = this.$refs.lbTable.pageSize
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          const query = {
            ...this._getQuery(this.query),
            currentPage,
            pageSize
          }
          if (this.query.date && this.query.date.length > 0) {
            query.lastBuyDt = this.query.date[0]
            query.lastBuyDtEnd = this.query.date[1]
          }
          const nowDate = new Date()
          query.lastSCheckDt = new Date(
            nowDate.setDate(nowDate.getDate() - this.selectTimeDay)
          )
          unCheckedCustomerExport({
            paramInfo: query,
            kv: str // 表格列
          }).then(res => {
            window.open(
              `${this.exportDomain}/page/export/frame?key=${res.data}`,
              '_blank'
            )
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  padding: 0;
  .orgTree {
    height: 820px;
  }
  .content {
    width: 0;
    padding: 10px 10px 0 10px;
    flex: 1;
  }
  .form {
    margin-left: 10px;
  }
}

.aside.open {
  width: 200px;
  font-size: 0.8rem;
}
</style>
